
var app=angular.module('qyMessageSend',[]);

app.config(function($httpProvider) {
    $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.transformRequest = [function(data) {
    	var param = function(obj) {
            var query = '';
            var name, value, fullSubName, subName, subValue, innerObj, i;
            for (name in obj) {
                value = obj[name];
 
                if (value instanceof Array) {
                    for (i = 0; i < value.length; ++i) {
                        subValue = value[i];
                        fullSubName = name + '[' + i + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                    }
                } else if (value instanceof Object) {
                   for (subName in value) {
                        subValue = value[subName];
                        
                        innerObj = {};
                        innerObj[subName] = subValue;//此处实现和jquery post方法提交值相同的方式
                        query += param(innerObj) + '&';
                    }
                	
                } else if (value !== undefined && value !== null) {
                    query += encodeURIComponent(name) + '='
                            + encodeURIComponent(value) + '&';
                }
            }
            return query.length ? query.substr(0, query.length - 1) : query;
        };
        return angular.isObject(data) && String(data) !== '[object File]'? param(data): data;
    }];
});
app.controller('qyMessageSendController',function($scope,$timeout,$http) {
	  $scope.getCookie=function(name){
		   	 var strCookie=document.cookie;
		   	 var arrCookie=strCookie.split("; ");
		   	 for(var i=0;i<arrCookie.length;i++){
		   	 var arr=arrCookie[i].split("=");
		   	     if(arr[0]==name){
		   	  	 	return arr[1];
		   	 	}
		   	 }
		   	 return "";
	  };
	
	  
	  $scope.mediaImageId="";//上传图片媒体ID
	  $scope.mediaFileId="";//
	  $scope.mediaVideoId="";
	  $scope.mediaVoiceId="";
	   $scope.initUploadBtn=function(K,type){
			var uploadbutton = K.uploadbutton({
				button : K('#btn_upload_'+type)[0],
				fieldName : 'imgFile',
				url : 'wechat/media/uploadQyMedia.htm?dir='+type,
				afterUpload : function(data) {
					$.unblockUI();
					if(data.errcode!=undefined){
						alert("上传失败！原因："+data.errmsg);return;
					}else {
						alert("上传成功！");
					}
					if(data.type=="image"){
						 $scope.mediaImageId=data.media_id;
					}else if(data.type=="file"){
						 $scope.mediaFileId=data.media_id;
					}else if(data.type=="video"){
						 $scope.mediaVideoId=data.media_id;
					}else if(data.type=="voice"){
						 $scope.mediaVoiceId=data.media_id;
					}
					
				},
				afterError : function(str) {
					alert("系统异常"+str);
				}
			});
			uploadbutton.fileBox.change(function(e) {
				$.blockUI({ message:'正在执行操作，请稍等...' });
				uploadbutton.submit();
			});
	   };
 
	    $scope.editor=null;
	    $scope.initEditor=function(){
	    	if($scope.editor==null){
				var sessionId=$scope.getCookie('JSESSIONID');
				KindEditor.ready(function(K) {
				    $scope.editor=K.editor({
					allowFileManager : true,
					uploadJson:'baseframework/util/editor/upload.htm;jsessionid='+sessionId, 
					fileManagerJson:'baseframework/util/editor/manage.htm;jsessionid='+sessionId
				    });
				   $scope.initUploadBtn(K,'image');
				   $scope.initUploadBtn(K,'voice');
				   $scope.initUploadBtn(K,'video');
				   $scope.initUploadBtn(K,'file');
				   $("#btnc01,#btnc02,#btnc03,#btnc04").hide();
				});
			}
	    }
	 $scope.initEditor();
	 
	 $scope.agentList=[{"agentid":"","name":"请选择"}];
	
	 $scope.loadAgentList=function(){//加载应用列表
		   $http.post('wechat/qy/agent/list.htm',{}).success(function(data, status, headers, config) {  
			   $scope.agentList=$scope.agentList.concat(data.agentlist);
			   $scope.agentId="";
		   }).error(function(data, status, headers, config) {
	    	   alert("操作失败,错误代码:"+status);  
		   });  
	  };
	  $scope.loadAgentList();
	  
	  
	  $scope.articles=[];
	  $scope.articles.push({"title":"标题","description":"","url":"","picurl":"","description":""});
	  
	  $scope.addArticle={"title":"","description":"","url":"","picurl":"","description":""};
	  $scope.editArticle={"title":"","description":"","url":"","picurl":"","description":""};
	
	  $scope.editArticleIndex=0;
	
	  
	  $scope.saveEditArticle=function(t){
		  if(t["title"]==undefined||t["title"]==""){
			  alert("标提不能为空");return;
		  }
		  if($scope.isURL(t.url)==false){
			  alert("链接非法");return;
		  }
		  if($scope.isURL(t.picurl)==false){
			  alert("图片路径非法");return;
		  }
	     $scope.articles[$scope.editArticleIndex]=t;
	     $("#editModal").modal("hide");
	  };
	  
	  $scope.deepCopy=function(source) { 
           var result={};
		    for (var key in source) {
     	      result[key] = typeof source[key]==='object'? deepCoyp(source[key]): source[key];
     	    } 
		   return result; 
	 };
	  
	  $scope.addArticle=function(t){
		
		  if(t["title"]==undefined||t["title"]==""){
			  alert("标提不能为空");return;
		  }
		  if($scope.isURL(t.url)==false){
			  alert("链接非法");return;
		  }
		  if($scope.isURL(t.picurl)==false){
			  alert("图片路径非法");return;
		  }
          if($scope.articles.length<8){
			  $scope.articles.push( $scope.deepCopy(t));
		  }
		  $("#addModal").modal("hide");
	  };
	  $scope.showAddModal=function(){
		  $("#addModal").modal("show");
	  }
	  
	  $scope.deleteEntity=function(index){
		  $scope.articles.splice(index, 1);
      };
	  
	  $scope.showEditModal=function(t,index){
		  $scope.editArticleIndex=index;
		  $scope.editArticle=t;
		  $("#editModal").modal("show");
	  }
	  $scope.isURL=function(url) {
		  var urlRegExp =/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i;
		   return urlRegExp.test(url);
	  }
	 	
	    /**
	     * 添加窗口显示图片对话框
	     */
	    $scope.showChooseImageWindowForAddArticle=function(){
				$scope.editor.loadPlugin('image', function() {
				$scope.editor.plugin.imageDialog({
					imageUrl : '',
					clickFn : function(url, title, width, height, border, align) {
						$scope.addArticle.picurl=url;
						$scope.editor.hideDialog();
					}
				});
			});
		};
		/**
		 * 编辑窗口显示图片对话框
		 */
	   $scope.showChooseImageWindowForEditArticle=function(){
				$scope.editor.loadPlugin('image', function() {
				$scope.editor.plugin.imageDialog({
					imageUrl : '',
					clickFn : function(url, title, width, height, border, align) {
						$scope.editArticle.picurl=url;
						$scope.editor.hideDialog();
					}
				});
			});
		};
		
		$scope.showTreeModal=function(){
			$("#treeModal").modal("show");
		};
		
		$scope.loadTreeData=function(){
			 $http.post('wechat/qy/txl/department/query.htm',{}).success(function(data, status, headers, config) {  
				 $scope.initTree(data);
			   }).error(function(data, status, headers, config) {
		    	   alert("操作失败,错误代码:"+status);  
			   });  
		};
		$scope.loadTreeData();
		$scope.initTree=function(data){
			$.fn.zTree.init($("#treeAdd"),{
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeClick: function(treeId,treeNode) {
						return true;
					},
					onClick: function(e, treeId, treeNode) {
					    $('#jquery-tagIt-primary-party').tagit("createTag",treeNode.name,null,null,treeNode.id);
					}
				}
			},data);
		};
		
		
		
		$scope.initTagIt=function(){
			$('#jquery-tagIt-primary-party').tagit({
		        availableTags: []
		    });
		};
		$scope.initTagIt();
		
		$scope.getUserTagId=function(tagname){
			 var tagid="";
			 angular.forEach($scope.userTagList, function(data,index,array){
			    	if(data.tagname==tagname){
			    		tagid=data.tagid;
			    	}
				});
			 return tagid;
		};
		
		$scope.userTagList=[];
		
		$scope.loadUserTagData=function(){
			 $http.post('wechat/tag/listQyTag.htm',{}).success(function(data, status, headers, config) {  
				 if(data.errcode==0){
					    $scope.userTagList=data.taglist;
					    var availableTags=[];
					    angular.forEach($scope.userTagList, function(data,index,array){
					    	availableTags.push(data.tagname);
						});
					    $('#jquery-tagIt-primary-user-tag').tagit({
					        availableTags: availableTags
					    });
				 }
			   }).error(function(data, status, headers, config) {
		    	   alert("操作失败,错误代码:"+status);  
			   });  
		};
		$scope.loadUserTagData();
		
		$scope.loadUserIdData=function(){
			 var params={};
			 params["departmentId"]="";
			 params["status"]=0;
			 params["limit"]=10;
			 params["offset"]=10;
			 $http.post('wechat/qy/txl/user/queryByDepartmentId.htm',{params:params}).success(function(data, status, headers, config) {  
                        var availableTags1=[];
					    angular.forEach(data.rows, function(data,index,array){
					    	availableTags1.push(data.userid);
						});
					    $('#jquery-tagIt-primary-user-id').tagit({
					        availableTags: availableTags1
					    });
				 
			   }).error(function(data, status, headers, config) {
		    	   alert("操作失败,错误代码:"+status);  
			   });  
		};
		$scope.loadUserIdData();
		
		
		
		$scope.getTagPartyList=function(){
			var retVal="";
			$("#jquery-tagIt-primary-party .tagit-label").each(function(){
				if($(this).attr("additionalValue")!="undefined"&&$(this).attr("additionalValue")!=""){
				   if(retVal==""){
					   retVal=retVal+$(this).attr("additionalValue");
				   }else{
					   retVal=retVal+"|"+$(this).attr("additionalValue");
				   }
				}
			});
			return retVal;
		};

		$scope.getTagUserIdList=function(){
			var retVal="";
			$("#jquery-tagIt-primary-user-id .tagit-label").each(function(){
				if($(this).attr("additionalValue")=="undefined"||$(this).attr("additionalValue")==""){
				   if(retVal==""){
					   retVal=retVal+$(this).text();
				   }else{
					   retVal=retVal+"|"+$(this).text();
				   }
				}
			});
			return retVal;
		};
		
		$scope.getTagUserTagList=function(){
			var retVal="";
			$("#jquery-tagIt-primary-user-tag .tagit-label").each(function(){
				if($(this).attr("additionalValue")=="undefined"||$(this).attr("additionalValue")==""){
				   if(retVal==""){
					   retVal=retVal+$scope.getUserTagId($(this).text());
				   }else{
					   retVal=retVal+"|"+$scope.getUserTagId($(this).text());
				   }
				}
			});
			return retVal;
		};
		
		$scope.getSentToParams=function(){
			var retVal={};
			retVal["toparty"]=$scope.getTagPartyList();
			retVal["touser"]=$scope.getTagUserIdList();
			retVal["totag"]=$scope.getTagUserTagList();
			retVal["agentid"]=$scope.agentId;
			return retVal;
		};
		
		$scope.getTextParams=function(){
			var retVal=$scope.getSentToParams();
			var text={};
			text["content"]=$scope.content;
			retVal["text"]=text;
			retVal["msgtype"]="text";
			retVal["safe"]="0";
			return retVal;
		};
		
		$scope.getImageParams=function(){
			var retVal=$scope.getSentToParams();
			var image={};
			image["media_id"]=$scope.mediaImageId;
			retVal["image"]=image;
			retVal["msgtype"]="image";
			retVal["safe"]="0";
			return retVal;
		};
		
		$scope.getVoiceParams=function(){
			var retVal=$scope.getSentToParams();
			var voice={};
			voice["media_id"]=$scope.mediaVoiceId;
			retVal["voice"]=voice;
			retVal["msgtype"]="voice";
			retVal["safe"]="0";
			return retVal;
		}

		$scope.getVideoParams=function(){
			var retVal=$scope.getSentToParams();
			var voice={};
			voice["media_id"]=$scope.mediaVideoId;
			retVal["voice"]=voice;
			retVal["msgtype"]="voice";
			retVal["safe"]="0";
			return retVal;
		}
		$scope.getFileParams=function(){
			var retVal=$scope.getSentToParams();
			var file={};
			file["media_id"]=$scope.mediaFileId;;
			retVal["file"]=file;
			retVal["msgtype"]="file";
			retVal["safe"]="0";
			return retVal;
		};

		$scope.getNewsParams=function(){
			var retVal=$scope.getSentToParams();
		    var news={};
		    var articles=new Array();
		    news["articles"]=$scope.articles;
		    retVal["news"]=news;
			retVal["msgtype"]="news";
			return retVal;
		};
		
		
		$scope.sendMessage=function(){
			    var submitData={};
				var i=0;
				$(".nav li").each(function(){
					i=i+1;
					if($(this).hasClass("active")){
						if(i==1){
							 submitData=$scope.getTextParams();
						}else if(i==2){
							 submitData=$scope.getNewsParams();
						}else if(i==3){
							 submitData=$scope.getImageParams();
						}else if(i==4){
							 submitData=$scope.getFileParams();
						}else if(i==5){
							 submitData=$scope.getVideoParams();
						}else if(i==6){
							 submitData=$scope.getVoiceParams();
						}
					}
				});
				// alert(JSON.stringify(submitData));
				
				if(parseInt(submitData["agentid"])!=submitData["agentid"]){
					alert('请选择发送应用!');return;
				}
				if(submitData["touser"]==""&&submitData["toparty"]==""&&submitData["totag"]==""){
					alert('接收用户,用户标签,接收部门不能同时为空!');return;
				}
				 var params={"json":JSON.stringify(submitData)};
				 
				 $.blockUI({ message:'正在执行操作，请稍等...' });
				 $http.post('wechat/message/sendQyMessage.htm',{params:params}).success(function(data, status, headers, config) {  
					   $.unblockUI();
					    if(data.errcode==0){
		 					alert('发送成功!');
		 				}else{
		 					alert(data.errmsg); 
		 				}
			    }).error(function(data, status, headers, config) {
			       $.unblockUI();
		    	   alert("操作失败,错误代码:"+status);  
			   });  	
				
		};
		
		$scope.imageUploadBtnClick=function(){
			$("#btnc01 input[type='file']").each(function(){
				if($(this).hasClass("ke-upload-file")){
					$(this).click();
				}
			});
		};
		$scope.voiceUploadBtnClick=function(){
			$("#btnc02 input[type='file']").each(function(){
				if($(this).hasClass("ke-upload-file")){
					$(this).click();
				}
			});
		};
		$scope.videoUploadBtnClick=function(){
			$("#btnc03 input[type='file']").each(function(){
				if($(this).hasClass("ke-upload-file")){
					$(this).click();
				}
			});
		};
		$scope.fileUploadBtnClick=function(){
			$("#btnc04 input[type='file']").each(function(){
				if($(this).hasClass("ke-upload-file")){
					$(this).click();
				}
			});
		};
		
		$scope.formatRepo=function  (repo) {
		    if (repo.loading) return repo.text;
		    var markup =repo.title;
		    return markup;
		  }

		 $scope.formatRepoSelection=function  (repo) {
		    return repo.name || repo.text;
	    }
	
		 $scope.getRootPath=function() {
	            //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
	            var curWwwPath = window.document.location.href;
	            //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
	            var pathName = window.document.location.pathname;
	            var pos = curWwwPath.indexOf(pathName);
	            //获取主机地址，如： http://localhost:8083
	            var localhostPaht = curWwwPath.substring(0, pos);
	            //获取带"/"的项目名，如：/uimcardprj
	            var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
	            return (localhostPaht + projectName);
	        }
		 
		
		
		$scope.createSelect2=function(selectId){
			$.fn.modal.Constructor.prototype.enforceFocus=function(){};//此行代码解决select2在模态窗口无法输入的bug
			var select=$("#"+selectId).select2({
					language: "zh-CN",
				    ajax: {
				      url: "cms/content/query.htm",
				      dataType: 'json',
				      delay: 250,
				      data: function (params) {
				    	  params["page"]=1;
				        return {
				          limit:100,
				          title: params.term, // search term
				          offset: params.page
				        };
				      },
				      processResults: function (data, params) {
				        // parse the results into the format expected by Select2
				        // since we are using custom formatting functions we do not need to
				        // alter the remote JSON data, except to indicate that infinite
				        // scrolling can be used
				        params.page = params.page || 1;
				        
				        var l=data.rows.length;
		                 for(var i=0;i<l;i++){
		                   	 data.rows[i]["text"]=data.rows[i].title;
		                 }
				         return {
				          results: data.rows,
				          pagination: {
				            more: (params.page * 30) < data.totalCount
				          }
				        };
				      },
				      cache: true
				    },
				    escapeMarkup: function (markup) { return markup; },
				    minimumInputLength: 1,
				    templateResult: $scope.formatRepo,
				    templateSelection: $scope.formatRepoSelection
				  });
				$(".select2-container--default").css({"width":"100%"});
				
				return select;
		};
		$scope.editContentSelect=$scope.createSelect2('editArticleContentSelect');
					
		$scope.addContentSelect=$scope.createSelect2('addArticleContentSelect');			
		  
       $scope.initSelect2=function(){
    	   $scope.editContentSelect.on("select2:select", function (e) {
				$http.post('cms/content/findByIdForWechat.htm',{params:{"id":$scope.editContentSelect.val()}}).success(function(data, status, headers, config) {  
						$scope.editArticle.url=$scope.getRootPath().concat("/").concat(data.url);
						$scope.editArticle.title=data.title;
						$scope.editArticle.description=data.subTitle;
             }).error(function(data, status, headers, config) {
			    	   alert("操作失败,错误代码:"+status);  
			   });  	
				
			}); 
    	   $scope.addContentSelect.on("select2:select", function (e) {
				$http.post('cms/content/findByIdForWechat.htm',{params:{"id":$scope.addContentSelect.val()}}).success(function(data, status, headers, config) {  
						$scope.addArticle.url=$scope.getRootPath().concat("/").concat(data.url);
						$scope.addArticle.title=data.title;
						$scope.addArticle.description=data.subTitle;
            }).error(function(data, status, headers, config) {
			    	   alert("操作失败,错误代码:"+status);  
			   });  	
				
			}); 
       };
		  
		$scope.initSelect2();
		
});




